package com.zhou.common.mybatis.template.shiro.file.zip;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;


@Slf4j
public class ZipUtils {

    //将文件压缩成Zip
    private static void zipFile(ZipOutputStream zipOut, String filePath, File file) throws Exception {
        log.debug("==> Zipping file = {}", file.getPath());
        if (!file.exists() || file.isDirectory()) {
            return;
        }
        String entryName = StringUtils.isEmpty(filePath) ? file.getName() : filePath + "/" + file.getName();
        zipOut.putNextEntry(new ZipEntry(entryName));
        FileInputStream fileIn = new FileInputStream(file);
        IOUtils.copy(fileIn, zipOut);

        fileIn.close();
        log.debug("<== Zipped entry = {}", entryName);
    }

    //解压缩
    public static void unZip(String sourcePath, String targetFileDirectory, String fileName, boolean deleteSourceFile) throws Exception {

        try (ZipFile zipFile = new ZipFile(sourcePath, Charset.forName("GBK"))) {
            File targetFile = new File(targetFileDirectory);
            if (!targetFile.exists()) {
                targetFile.mkdir();
            }
            for (Enumeration<? extends ZipEntry> entries = zipFile.entries(); entries.hasMoreElements(); ) {
                ZipEntry zipEntry = entries.nextElement();
                File outputFilePath = new File(targetFileDirectory + File.separator + zipEntry.getName());
                try (InputStream inputStream = zipFile.getInputStream(zipEntry)) {
                    try (OutputStream os = new FileOutputStream(outputFilePath)) {
                        IoUtil.copy(inputStream, os);
                    }
                }
            }
        }

        if (deleteSourceFile) {
            FileUtil.del(FileUtil.normalize(sourcePath));
        }
    }

    public static void main(String[] args) throws Exception {

        FileOutputStream fos = new FileOutputStream("D:/home/zxf.zip");
        FileInputStream fis = new FileInputStream("D:/home/excel/ExcelExportStatisticTest.export.xlsx");
        ZipOutputStream out = new ZipOutputStream(fos);
        File file = new File("D:/home/excel/ExcelExportStatisticTest.export.xlsx");
        //单个文件压缩
        zipFile(out, "", file);
        out.flush();
        out.close();
        fos.close();
        //单个文件解压
        unZip("D:/home/zxf.zip", "D:/home", "xf.xlsx", false);

        FileOutputStream fos1 = new FileOutputStream("D:/home/zxf111.zip");

        ZipOutputStream out1 = new ZipOutputStream(fos1);
        //目录压缩
        compress(out1, new File("D:\\home\\lemur"), "");
        out1.flush();
        IoUtil.close(out1);
        //目录解压
        unZipFiles(new File("D:/home/zxf111.zip"), "D:/home/");

    }

    public static void compress(ZipOutputStream out, File sourceFile, String base) {
        FileInputStream fos = null;
        BufferedInputStream bis = null;
        try {
            //如果路径为目录（文件夹）
            if (sourceFile.isDirectory()) {
                //取出文件夹中的文件（或子文件夹）
                File[] flist = sourceFile.listFiles();
                if (flist.length == 0) {//如果文件夹为空，则只需在目的地zip文件中写入一个目录进入点
                    out.putNextEntry(new ZipEntry(base + "/"));
                } else {//如果文件夹不为空，则递归调用compress，文件夹中的每一个文件（或文件夹）进行压缩
                    for (int i = 0; i < flist.length; i++) {
                        if (StringUtils.isBlank(base)) {
                            compress(out, flist[i], flist[i].getName());
                        } else {
                            compress(out, flist[i], base + "/" + flist[i].getName());
                        }

                    }
                }
            } else {//如果不是目录（文件夹），即为文件，则先写入目录进入点，之后将文件写入zip文件中
                out.putNextEntry(new ZipEntry(base));
                fos = new FileInputStream(sourceFile);
                bis = new BufferedInputStream(fos);

                int tag;
                //将源文件写入到zip文件中
                while ((tag = bis.read()) != -1) {
                    out.write(tag);
                }
                bis.close();
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IoUtil.close(bis);
            IoUtil.close(fos);
        }
    }


    public static void unZipFiles(File zipFile, String descDir) throws IOException {
        ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));//解决中文文件夹乱码
        String name = zip.getName().substring(zip.getName().lastIndexOf('\\') + 1, zip.getName().lastIndexOf('.'));
        File pathFile = new File(descDir + name);

        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }

        for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements(); ) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            String zipEntryName = entry.getName();
            InputStream in = zip.getInputStream(entry);
            String outPath = (descDir + name + "/" + zipEntryName).replaceAll("\\*", "/");
            // 判断路径是否存在,不存在则创建文件路径
            File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
            if (!file.exists()) {
                file.mkdirs();
            }

            // 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
            if (new File(outPath).isDirectory()) {
                continue;
            }
            // 输出文件路径信息
            // System.out.println(outPath);
            FileOutputStream out = new FileOutputStream(outPath);
            byte[] buf1 = new byte[1024];
            int len;
            while ((len = in.read(buf1)) > 0) {
                out.write(buf1, 0, len);
            }
            in.close();
            out.close();
        }
        System.out.println("******************解压完毕********************");
    }


}

